package thread;

import java.sql.Array;
import java.util.ArrayList;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

class MyThreadPool{
    BlockingQueue<Runnable> taskQue = null;
    ArrayList<Thread> threadPool = null;
    public MyThreadPool(int capacity, int nrThread){
        taskQue = new ArrayBlockingQueue<>(capacity);
        threadPool = new ArrayList<>(nrThread);
        for(int i = 0; i < nrThread; ++i){
            threadPool.add(new Thread(()->{
                Runnable task = null;
                try {
                    while(true){
                        task = taskQue.take();
                        task.run();
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }));
//            threadPool.get(i).setDaemon(true);
            threadPool.get(i).start();
        }
    }
    public void submit(Runnable task) throws InterruptedException{
        taskQue.put(task);
    }

}


public class Demo11_MyThreadPool {
    public static void main(String[] args) throws InterruptedException {
        MyThreadPool tp = new MyThreadPool(50,5);
        for(int i = 0; i < 100; ++i){
            int id = i;
            tp.submit(()->{
                System.out.println(Thread.currentThread().getName()+" consumed " + id);
            });
        }
    }
}
